﻿using System;
using System.Linq;
using Castle.ActiveRecord.Framework;

namespace FileManager_Server.DataLayer.Repository
{
    public class Repository : IRepository
    {

        public void Add<T>(T entity) where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            entity.SaveAndFlush();
        }

        public long Count<T>() where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            return (from c in ActiveRecordLinq.AsQueryable<T>() select c).Count();
        }

        public long Count<T>(System.Linq.Expressions.Expression<System.Func<T, bool>> expression) where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            return (from c in ActiveRecordLinq.AsQueryable<T>() select c).Where(expression).Count();
        }

        public void Delete<T>(T entity) where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            entity.DeleteAndFlush();
        }

        public System.Collections.Generic.IList<T> GetAll<T>() where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            return (from c in ActiveRecordLinq.AsQueryable<T>() select c).ToList();
        }

        public System.Collections.Generic.IList<T> GetAll<T>(System.Linq.Expressions.Expression<System.Func<T, bool>> expression) where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            return (from c in ActiveRecordLinq.AsQueryable<T>() select c).Where(expression).ToList();
        }

        public T GetSingle<T>(System.Linq.Expressions.Expression<System.Func<T, bool>> expression) where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            return (from c in ActiveRecordLinq.AsQueryable<T>() select c).FirstOrDefault(expression);
        }

        public void Update<T>(T entity) where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            entity.UpdateAndFlush();
        }

        public void UpdateList<T>(System.Collections.Generic.List<T> entitys) where T : Castle.ActiveRecord.ActiveRecordBase<T>
        {
            foreach (var entity in entitys)
            {
                entity.UpdateAndFlush();
            }
        }

        public void Dispose()
        {
            
        }
    }
}